package cn.com.fig.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.jdbc.StringUtils;

import cn.com.fig.common.PaginationReqParam;
import cn.com.fig.common.PaginationResponse;
import cn.com.fig.common.ReplyMsg;
import cn.com.fig.mybatis.DbUtils;

@Service
public class BaseService {
	@Autowired
	private DbUtils dbUtils;
	

	/**
	 * 分页查询
	 * @param reqParam
	 * @param sysId
	 * @param privilegeName
	 * @return
	 */
	public PaginationResponse<Map<String,Object>> queryList(String statement,Map<String,Object> param,PaginationReqParam reqParam){
		if(reqParam.isNeedSplitPage())
			PageHelper.startPage(reqParam.getStartIndex(), reqParam.getRows());		
	
		List<Map<String,Object>> list = dbUtils.queryList(statement,param);
		PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(list);
		
		PaginationResponse<Map<String,Object>> res = new PaginationResponse<Map<String,Object>>();
		res.setNumPerPage(reqParam.getRows());
		res.setRows(list);
		res.setTotalRows(page.getTotal());
		return res;
	}

	public ReplyMsg insertBatch(String statement,List<Map<String,Object>> param){
		int ret = 0;
		ReplyMsg msg = new ReplyMsg();
		ret = dbUtils.insertBatch(statement,param);
		if(ret <1){
			msg.setRetCode("-1");
			msg.setRetMsg("保存系统数据失败！");
		}
		return msg;
	}
	/**
	 * 新增或更新方法
	 * @param statement
	 * @param department
	 * @return
	 */
	public ReplyMsg save(String statement,Map<String,Object> param){
		int ret = 0;
		ReplyMsg msg = new ReplyMsg();

		if(param.containsKey("parentId")){
			String parentId = (String)param.get("parentId");
			if(parentId != null && "".equals(parentId.trim())){
				param.put("parentId", null);
			}
		}
		String insertMark = param.get("insertMark").toString();//1插入；0更新
		if(insertMark == null || insertMark.equals("1")){		
			ret = dbUtils.insert(statement,param);
		}else{
			ret = dbUtils.update(statement,param);
		}
		if(ret <1){
			msg.setRetCode("-1");
			msg.setRetMsg("保存系统数据失败！");
		}
		return msg;
	}
	/**
	 * 删除方法
	 * @param statement
	 * @param priId
	 * @return
	 */
	public ReplyMsg del(String statement,String priId){
		int ret = 0;
		ReplyMsg msg = new ReplyMsg();
		
		if(StringUtils.isNullOrEmpty(priId)){
			msg.setRetCode("-1");
			msg.setRetMsg("请选择要删除的记录");
			return msg;
		}
		
		ret = dbUtils.delete(statement,priId);
		if(ret <1){
			msg.setRetCode("-1");
			msg.setRetMsg("删除组织机构数据失败！");
		}
		return msg;
	}
}
